import { fileURLToPath, URL } from 'node:url'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import viteCompression from 'vite-plugin-compression'
import { createHtmlPlugin } from 'vite-plugin-html'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { viteMockServe } from 'vite-plugin-mock'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'
import path from 'path'

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  // 根据当前工作目录中的 `mode` 加载 .env 文件
  const env = loadEnv(mode, process.cwd(), '')
  
  return {
    base: '/',
    define: {
      // 定义全局常量
      __APP_ENV__: JSON.stringify(env.VITE_APP_MODE),
      // Vue-i18n 特性标志替换
      __VUE_I18N_FULL_INSTALL__: true,
      __VUE_I18N_LEGACY_API__: false,
      __INTLIFY_PROD_DEVTOOLS__: false,
    },
    plugins: [
      vue(),
      // HTML模板注入
      createHtmlPlugin({
        inject: {
          data: {
            title: env.VITE_APP_TITLE,
          },
        },
      }),
      // SVG图标插件
      createSvgIconsPlugin({
        iconDirs: [
          path.resolve(process.cwd(), 'src/assets/svg/icons'),
          path.resolve(process.cwd(), 'src/assets/svg/colored')
        ],
        symbolId: 'icon-[dir]-[name]',
      }),
      // 自动导入Composition API
      AutoImport({
        imports: [
          'vue',
          'vue-router',
          'pinia',
          'vue-i18n'
        ],
        dts: 'src/types/auto-imports.d.ts',
      }),
      // 自动导入组件
      Components({
        resolvers: [
          AntDesignVueResolver({
            importStyle: false,
          }),
        ],
        dts: 'src/types/components.d.ts',
      }),
      // Mock服务
      viteMockServe({
        mockPath: 'mock',
        enable: env.VITE_MOCK_ENABLED === 'true',
        watchFiles: true,
      }),
      // GZIP压缩
      viteCompression({
        verbose: true,
        disable: false,
        threshold: 10240,
        algorithm: 'gzip',
        ext: '.gz',
      }),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        '@mock': fileURLToPath(new URL('./mock', import.meta.url))
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
          modifyVars: {
            'primary-color': '#1890ff',
            'link-color': '#1890ff',
            'success-color': '#52c41a',
            'warning-color': '#faad14',
            'error-color': '#f5222d',
            'border-radius-base': '4px',
          },
        },
        scss: {
          additionalData: `@use "sass:math"; @import "@/assets/styles/common/variables.scss";`,
        },
      },
    },
    server: {
      host: '0.0.0.0',
      port: 3000,
      open: true,
      proxy: {
        // 代理API请求
        '/api': {
          target: 'http://localhost:3000',
          changeOrigin: true,
        },
      },
    },
    build: {
      outDir: 'dist',
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: env.VITE_APP_MODE === 'production',
          drop_debugger: env.VITE_APP_MODE === 'production',
        },
      },
      assetsInlineLimit: 4096,
      cssCodeSplit: true,
      sourcemap: env.VITE_APP_MODE !== 'production',
      rollupOptions: {
        output: {
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
          manualChunks: {
            vue: ['vue', 'vue-router', 'pinia', 'vue-i18n'],
            antd: ['ant-design-vue', '@ant-design/icons-vue'],
            icons: ['@/assets/svg'],
            utils: ['@/utils', '@/hooks'],
          },
        },
      },
    },
  }
})
